package com.qjc.controller;

import com.qjc.feign.AccountService;
import com.qjc.feign.OrderService;
import com.qjc.feign.StorageService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 主业务类
 * http://localhost:18081/fescar/feign
 */
@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE, RequestMethod.PUT})
@Slf4j
public class HomeController {

    private static final String SUCCESS = "SUCCESS";
    private static final String FAIL = "FAIL";
    private static final String USER_ID = "1";
    private static final String COMMODITY_CODE = "2001";
    private static final int ORDER_COUNT = 5;
    private static final int MONEY = 10;
    @Resource
    OrderService orderService;
    @Resource
    StorageService storageService;
    @Resource
    AccountService accountService;


    @GlobalTransactional(timeoutMills = 300000, name = "spring-cloud-demo-tx")
    @RequestMapping(value = "/fescar/feign", method = RequestMethod.GET, produces = "application/json")
    public String feign() {
        //输出全局事务ID
        log.info("business Service Begin ... xid: " + RootContext.getXID());
        String result = storageService.storage(COMMODITY_CODE,5);

        if (!SUCCESS.equals(result)) {
            throw new RuntimeException("调用仓储微服务出现异常");
        }

        result = orderService.order(USER_ID, COMMODITY_CODE, ORDER_COUNT);

        if (!SUCCESS.equals(result)) {
            throw new RuntimeException("调用订单微服务出现异常");
        }

        result = accountService.updateMoney(USER_ID, MONEY);

        if (!SUCCESS.equals(result)) {
            throw new RuntimeException("调用账户微服务出现异常");
        }
        //异常
        int a = 1/0;
        return SUCCESS;
    }
}
